from database.models import Comment
from user.login import check_auth
from django.http import HttpRequest, JsonResponse, HttpResponse
from utils import baidu_access_token
import json
import requests


def comment_check(comment: str) -> bool:
    request_url = f"https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token={baidu_access_token}"
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data={"text": comment}, headers=headers)
    if response.json().get('conclusionType') != 1:
        return False
    return True


def add_comment(request: HttpRequest):
    payload = json.loads(request.body)
    video_id = payload.get('id')
    comment = payload.get('comment')
    id = check_auth(payload.get('token'))
    if type(id) != int:
        return HttpResponse(str(id), status=400)

    Comment.objects.create(user_id=id, video_id=video_id, content=comment, allowed=comment_check(comment))
    return HttpResponse('success')


def del_comment(request: HttpRequest):
    id = check_auth(request.GET.get('token'))
    comment_id = request.GET.get('comment_id')
    if type(id) != int:
        return HttpResponse(str(id), status=400)

    com_obj = Comment.objects.filter(user_id=id, id=comment_id).first()

    if com_obj is not None:
        Comment.delete(com_obj)
        return HttpResponse('success')
    return HttpResponse('Invalid operation', status=400)


def get_vid_comment(request: HttpRequest):
    token = request.GET.get('token')
    video_id = request.GET.get('id')

    user_id = -1
    if token and type(check_auth(token)) == int:
        user_id = check_auth(token)

    comments = Comment.objects.filter(video_id=video_id, allowed=True).all()

    return JsonResponse({'payload': [{'id': i.id, 'user': i.user.user_name, 'content': i.content, 'time': i.time,
                                      'self': True if user_id == i.user.user_id else False} for i in comments]})


def get_usr_comment(request: HttpRequest):
    id = check_auth(request.GET.get('token'))
    if type(id) != int:
        return HttpResponse(str(id), status=400)

    comments = Comment.objects.filter(user_id=id).all()

    return JsonResponse({'payload': [{'id': i.id, 'user': i.user.user_name, 'content': i.content, 'time': i.time,
                                      'allowed': i.allowed} for i in comments]})
